#!/bin/bash
cd /opt

source /home/shell/util.sh

local_url=http://192.168.100.59/download/jdk

function openjdk () {
  clear
  printInfo "版本列表："
  curl -sL https://repo.huaweicloud.com/openjdk/|grep -Po ">.*</a>"|grep -v java|perl -pe "s/.*\>(.*)\/<.*/\1/g"
  while [ true ]; do
      read -p "请选择版本：" version
      if [[ -z "${version}" ]]; then
          printFail "请重新输入版本！"
          continue;
      else
          break;
      fi
  done
  if [ ! -f "/opt/jdk.tar.gz" ]; then
    download /opt/jdk.tar.gz https://repo.huaweicloud.com/openjdk/${version}/openjdk-${version}_linux-x64_bin.tar.gz
  else
    printWarn "安装包已存在，跳过下载。"
  fi
}

function oraclejdk () {
  if [ ! -f "/opt/jdk.tar.gz" ]; then
    download /opt/jdk.tar.gz https://mirrors.huaweicloud.com/java/jdk/8u202-b08/jdk-8u202-linux-x64.tar.gz
    else
  printWarn "安装包已存在，跳过下载。"
  fi
}

function oraclejdk_local () {
  printInfo "版本列表："
  curl -sL ${local_url}|grep -e "\s*M"|perl -pe "s/.*>(.*)<.*/\1/g"
  while [ true ]; do
      read -p "请选择版本：" version
      if [[ -z "${version}" ]]; then
          printFail "请重新输入版本！"
          continue;
      else
          break;
      fi
  done
  if [ ! -f "/opt/jdk.tar.gz" ]; then
    download /opt/jdk.tar.gz ${local_url}/${version}
  else
    printWarn "安装包已存在，跳过下载。"
  fi
}


function localUpload () {
  cd /opt
  rz
  mv ./jdk*bin.tar.gz ./jdk.tar.gz
}

cat <<EOF
  1. 安装OpenJDK
  2. 安装OracleJDK(华为云)
  3. 安装OracleJDK(本地服务器)
  4. 本地上传
EOF
while [ true ]; do
  read -p "请选择：" install_option
  case "${install_option}" in
    1)
      openjdk
      break;
    ;;
    2)
      oraclejdk
      break;
    ;;
    3)
      oraclejdk_local
      break;
    ;;
    4)
      localUpload
      break;
    ;;
    *)
      printFail "选择错误，重新选择。"
    ;;
  esac
  
done


tar -xf ./jdk.tar.gz
rm -rf ./jdk.tar.gz
mv ./jdk* ./jdk

tee /etc/profile.d/java.sh<<EOF
export JAVA_HOME="/opt/jdk"
export PATH="\$JAVA_HOME/bin:\$PATH"
export spring_profiles_active=test
EOF

source /etc/profile.d/java.sh
printInfo "安装完毕！Java版本信息："
java -version